package algutil.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

public class Balise {

	private static final Logger log = Logger.getLogger(Balise.class);

	private String nom;

	private List<Balise> noeuds;

	private String htmlDoc;

	private String baliseCode;

	private String contenu;

	private List<Parametre> params;

	public Balise() {
	}

	public Balise(String nom) {
		this.nom = nom;
	}

	public void parse(String htmlDoc) {

		String balise = getNextBalise(htmlDoc);
		log.info(balise);
		parserBalise(balise);
		htmlDoc = htmlDoc.replaceFirst(balise, "").trim();

		/*String contenu = htmlDoc.substring(posD + 1,
				htmlDoc.indexOf("<", posD + 1)).trim();
		if (contenu.length() > 0) {
			log.info("  contenu='" + contenu + "'");
		}*/

		balise = getNextBalise(htmlDoc);
		log.info(balise);
		parserBalise(balise);

		/*
		 * posF = posD;
		 * 
		 * for (int i = 0; i < 100; i++) { posD = htmlDoc.indexOf(">", posF +
		 * 1); // log.info(htmlDoc.indexOf("<", posC)+" "+pos); balise =
		 * htmlDoc.substring(htmlDoc.indexOf("<", posF), posD + 1);
		 * log.info(balise); String contenu = htmlDoc.substring(posD + 1,
		 * htmlDoc.indexOf("<", posD + 1)).trim(); if (contenu.length() > 0) {
		 * log.info("  contenu='" + contenu + "'"); } posF = posD; i++; }
		 */
	}

	private void parserBalise(String balise) {

		StringTokenizer st = new StringTokenizer(balise, " <>");
		boolean nameFound = false;
		while (st.hasMoreTokens()) {
			if (!nameFound) {
				log.info("Nom : " + st.nextToken());
				setNom(balise);
				nameFound = true;
			} else {
				addParameter(st.nextToken());
			}
		}
	}

	private void addParameter(String parameter) {

		StringTokenizer st = new StringTokenizer(parameter, "=\"");
		String id = null;
		String value = null;
		if (st.hasMoreTokens()) {
			id = st.nextToken();
		}
		if (st.hasMoreTokens()) {
			id = st.nextToken();
		}

		if (params == null) {
			params = new ArrayList<Parametre>();
		}
		params.add(new Parametre(id, value));
	}

	private String getNextBalise(String htmlDoc) {

		String balise = htmlDoc.substring(htmlDoc.indexOf("<"),
				htmlDoc.indexOf(">") + 1).trim();
		// log.info(balise);
		return balise;
	}

	public String getNom() {
		return nom;
	}

	public void setNom(String nom) {
		this.nom = nom;
	}

	public List<Balise> getNoeuds() {
		return noeuds;
	}

	public void setNoeuds(List<Balise> noeuds) {
		this.noeuds = noeuds;
	}

	public String getHtmlDoc() {
		return htmlDoc;
	}

	public void setHtmlDoc(String htmlDoc) {
		this.htmlDoc = htmlDoc;
	}
}
